package cn.xx.ai4.controller;

import cn.xx.ai4.service.RealtimeRecognitionTask;
import cn.xx.ai4.service.ResultHandler;
import com.alibaba.dashscope.audio.asr.translation.results.TranslationRecognizerResult;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class SpeechController {

    @GetMapping(value = "/speech", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter speech () throws InterruptedException {
        SseEmitter emitter = new SseEmitter(60_000L); // 设置超时时间
        ResultHandler resultHandler = new ResultHandler() {
            @Override
            public void handleResult(TranslationRecognizerResult result) {
                System.out.println("RequestId: " + result.getRequestId());
                // 打印最终结果
                if (result.getTranscriptionResult() != null) {
                    String transcription = result.getTranscriptionResult().getText();
                    try {
                        emitter.send(SseEmitter.event()
                                .name("transcription")
                                .data(transcription));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            @Override
            public void onComplete() {
                // 发送结束事件
                try {
                    emitter.send(SseEmitter.event().name("end").data("事件结束"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                emitter.complete(); // 通知客户端流结束
            }

            @Override
            public void onError(Exception e) {
                emitter.completeWithError(e); // 发送错误信息
            }
        };

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new RealtimeRecognitionTask(resultHandler));
        executorService.shutdown();
        executorService.awaitTermination(5, TimeUnit.SECONDS);

        // 处理客户端断开连接
        emitter.onCompletion(() -> {
            System.out.println("客户端断开连接");
            executorService.shutdownNow();
        });

        return emitter;
    }
}
